<template>
  <div class="change-password-container">
    <el-card class="change-password-card">
      <h2 class="title">修改密码</h2>
      <el-form :model="form" ref="form" label-width="80px">
        <el-form-item label="旧密码">
          <el-input type="password" v-model="form.oldPassword" autocomplete="off" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="form.newPassword" autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input type="password" v-model="form.confirmPassword" autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { changePassword } from '@/api/userService';

export default {
  data() {
    return {
      form: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      loading: false,
    };
  },
  methods: {
    async submitForm() {
      if (this.form.newPassword !== this.form.confirmPassword) {
        this.$message.error("新密码和确认密码不一致");
        return;
      }

      this.loading = true;
      try {
        const response = await changePassword({
          oldPassword: this.form.oldPassword,
          newPassword: this.form.newPassword,
        });
        if (response.code === 200) {
          this.$message.success("修改密码成功");
          // 重置表单
          this.form.oldPassword = "";
          this.form.newPassword = "";
          this.form.confirmPassword = "";
        } else {
          this.$message.error(response.message || "修改密码失败");
        }
      } catch (error) {
        this.$message.error("网络错误，请稍后再试");
        console.error("Error changing password:", error);
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.change-password-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  background-color: #37466d;
}

.change-password-card {
  width: 400px;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
}
</style>
